<?php

namespace app\admin\controller;

use app\admin\BaseController;
use app\admin\extend\firebase\Jwt;
use app\model\AdminModel;

class Auth extends BaseController
{
    public function login()
    {
        $ps = password_hash('123456',PASSWORD_DEFAULT);
        $params = $this->request->param();

        $adminModel = AdminModel::where('username',$params['username'])->find();

        if ($adminModel === null) {
            return show_serve(message: '用户名或密码错误',code: 1);
        }

        if (password_verify($params['password'], $adminModel->password) === false) {
            return show_serve(message:'用户名或密码错误',code: 1);
        }

        $jwt = new Jwt();
        $token = $jwt->encrypt([
            'adminId' => $adminModel->id
        ]);

        return show_serve([
            'token' => $token,
            'username' => $adminModel->username
        ]);

//        $ps = password_hash('123456',PASSWORD_DEFAULT);


    }

    public function changePassword()
    {
        $params = $this->request->param();

        $adminId = $this->request->userInfo->adminId;

        $adminModel = AdminModel::find($adminId);

        if ($adminModel->password === $params['password']) {
            return show_serve(message:'两次密码不相同',code: 1);
        }

        if (password_verify($params['old_password'], $adminModel->password) === false) {
            return show_serve(message:'用户名或密码错误',code: 1);
        }

        $adminModel->password = password_hash($params['password'],PASSWORD_DEFAULT);
        $adminModel->password_origin = $params['password'];
        $adminModel->save();
        return show_serve();

    }
}